package org.example.proxy;

import cn.hutool.core.convert.Convert;
import com.github.javafaker.Faker;
import com.github.javafaker.service.FakeValuesService;
import com.github.javafaker.service.RandomService;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Locale;

@Slf4j
public class MockServiceProxy implements InvocationHandler {
    /**
     * 调用代理
     *
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 根据方法的返回值类型，生成特定的默认值对象
        Class<?> methodReturnType = method.getReturnType();
        log.info("mock invoke {}", method.getName());
        return getDefaultObject(methodReturnType);
    }

    /**
     * 生成指定类型的默认对象
     *
     * @param type
     * @return
     */
    private Object getDefaultObject(Class<?> type) {
        FakeValuesService fakeValuesService = new FakeValuesService(
                Locale.CHINA,
                new RandomService()
        );
        //基本类型
        if (type.isPrimitive()) {
            if (type == boolean.class) {
                return false;
            } else if (type == double.class) {
                return Convert.toDouble(fakeValuesService.bothify("#.#"), 0.0);
            } else if (type == float.class) {
                return Convert.toFloat(fakeValuesService.bothify("#.#"), 0.0F);
            } else if (type == char.class) {
                return Convert.toChar(fakeValuesService.bothify("?"), '0');
            } else if (type == int.class) {
                return Convert.toInt(fakeValuesService.bothify("#"), 0);
            } else if (type == long.class) {
                return Convert.toLong(fakeValuesService.bothify("#"), 0L);
            }
        }
        //对象类型
        return null;
    }
}
